var app = getApp();
const db = wx.cloud.database();
const command = db.command;
wx.cloud.init({
  env: 'wccloud-fm7zt'
})
Page({
  data: {
    // 从数据库读取到的聊天消息列表
    latestnews: [],
    items: [],
    startX: 0, //开始坐标
    startY: 0,
    worker: '',

  },
  get_messagelist: function () {
    wx.getStorage({
      key: 'nickName',
    }).then(res => {
      // console.log(res.data);
      this.setData({
        worker: res.data
      })
      db.collection('chatroom').where({
          userB: res.data
        })
        .get()
        .then(res => {
          var items = [];
          var latestnews = [];
          for (let num = 0; num < res.data.length; num++) {
            // 下面这一行就是最新的消息
            // console.log(res.data[num].detail[res.data[num].detail.length-1]);
            items.push(res.data[num])
            // console.log(items);
            latestnews.push(res.data[num].detail[res.data[num].detail.length - 1])
          }
          // console.log(items);
          // console.log(latestnews);
          this.setData({
            items,
            latestnews,
          })
          const _this = this;
          db.collection('chatroom').where({
              userB: this.data.worker,
            })
            .watch({
              onChange: function (snapshot) {
                var items = [];
                var latestnews = [];
                // console.log(snapshot.docs);
                for (let num = 0; num < snapshot.docs.length; num++) {
                  var userA = snapshot.docs[num];
                  // 下面这一行是聊天对象
                  // console.log(userA);
                  items.push(userA)
                  // 下面这一行是聊天的最后一条消息
                  // console.log(snapshot.docs[num].detail[snapshot.docs[num].detail.length - 1].news_centent);
                  latestnews.push(snapshot.docs[num].detail[snapshot.docs[num].detail.length - 1])
                }
                // console.log(items);
                // console.log(latestnews);
                _this.setData({
                  items,
                  latestnews,
                })
              },
              onError: function (err) {
                console.error('the watch closed because of error', err)
              },
            })
        })
    })
  },



  chatwith: function (e) {
    // console.log(this.data.items[e.currentTarget.dataset.index].userA);
    wx.navigateTo({
      url: '../../pages/chat_page1/chat_page1?userB=' + this.data.items[e.currentTarget.dataset.index].userA + '&userA=' + this.data.worker,
    })
  },


  onLoad: function () {
    this.get_messagelist();


  },

  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.items.forEach(function (v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      items: this.data.items
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    that.data.items.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      items: that.data.items
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //删除事件
  del: function (e) {
    // console.log(e.currentTarget.dataset.index);
    // console.log(this.data.items[e.currentTarget.dataset.index]);
    var userA = this.data.items[e.currentTarget.dataset.index].userA;
    var userB = this.data.items[e.currentTarget.dataset.index].userB;
    wx.showModal({
      title: '提示',
      content: '是否确认删除',
    }).then(res => {
      console.log(res);
      if (res.confirm) { //用户点击了确认删除按钮
        // 这个就是点击了删除按钮的新闻的ID，通过这个ID删除数据库的数据
        wx.cloud.callFunction({
          name:'update',
          data:{
            options:'del_chatmessage',
            userA:userA,
            userB:userB,
          }
        }).then(res=>{
          // console.log(res.data);
        })
      } else if (res.cancel) { //用户点击了取消按钮
        console.log("用户点击取消删除");
      }
    })
  },
})